package com.fitzone.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fitzone.common.context.UserContext;
import com.fitzone.common.exception.BaseException;
import com.fitzone.common.exception.LoginFailedException;
import com.fitzone.common.properties.WeChatProperties;
import com.fitzone.common.utils.HttpClientUtil;
import com.fitzone.common.utils.QRCodeUtil;
import com.fitzone.model.dto.UserDTO;
import com.fitzone.model.entity.User;
import com.fitzone.web.mapper.UserMapper;
import com.fitzone.web.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    //微信服务接口地址
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final WeChatProperties weChatProperties;
    private final UserMapper userMapper;

    @Override
    public User wxLogin(String code) {
        String openid = getOpenid(code);
        if (openid == null) {
            throw new LoginFailedException("获取openid失败");
        }

        // 根据openid查询用户
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getOpenid, openid);
        User user = userMapper.selectOne(userLambdaQueryWrapper);

        // 没有就新增
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .name("FZ_" + new Random().nextInt(90000) + 10000)
                    .build();
            userMapper.insert(user);
        }
        return user;
    }

    private String getOpenid(String code) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }


    @Override
    @Transactional
    public void updateUser(UserDTO userDTO) {
        if (userDTO == null) {
            throw new BaseException("请输入要修改的内容");
        }
        User user = new User();
//        user.setName(userDTO.getName());
//        user.setPhone(userDTO.getPhone());
//        user.setSex(userDTO.getSex());
        BeanUtils.copyProperties(userDTO, user);
        this.updateById(user);
    }

    @Override
    public User getQrcode() {
        Long currentId = UserContext.getCurrentId();
        User user = userMapper.selectById(currentId);
        return user;
    }
}
